package me.zhengjie.modules.fund.service.impl;

import lombok.extern.slf4j.Slf4j;
import me.zhengjie.modules.fund.domain.StockNetValue;
import me.zhengjie.modules.fund.repository.StockNetValueRepository;
import me.zhengjie.modules.fund.service.StockNetValueService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class StockNetValueServiceImpl implements StockNetValueService {

    @Resource
    private StockNetValueRepository stockNetValueRepository;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(List<StockNetValue> resources) {
        if (CollectionUtils.isEmpty(resources)) {
            return;
        }

        for (StockNetValue netValue : resources) {
            StockNetValue exists = stockNetValueRepository.findByCodeAndDate(netValue.getCode(), netValue.getDate());
            if (Objects.isNull(exists)) {
                stockNetValueRepository.save(netValue);
            } else {
                netValue.setId(exists.getId());
                stockNetValueRepository.save(netValue);
            }
        }
    }
}
